package com.epalmpay.commom;

import com.epalmpay.util.Tools;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

/**
 * Created by lifayi on 2017/5/10.
 */
@Controller
public class FileUploadContorller {

    @Value("${fileServerDir}")
    private String fileServerDir;

    @Value("${fileLocalPath}")
    private String fileLocalPath;

    @Value("${fileServerURL}")
    private String fileServerURL;

    @Value("${accessFileURL}")
    private String accessFileURL;

    @RequestMapping(value="/merchant/system/fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletResponse response) {
        response.setContentType("text/html; charset=utf-8");

        if(Tools.isEmpty(path)) {
            return "error|path parameter is required";
        }
        if(!path.startsWith("/")) {
            path = "/" + path;
        }

        path = fileServerDir + path;

        if(!path.endsWith("/")) {
            path += "/";
        }

        String[] suffixes = { "BMP", "JPG", "JPEG", "PNG", "GIF","XLS"};
        String name = file.getOriginalFilename();
        int length = name.length();
        boolean flg = false;
        for (String suffix : suffixes) {
            if (name.substring(name.indexOf(".") + 1, length).equalsIgnoreCase(
                    suffix)) {
                flg = true;
                break;
            }
        }
        if (!flg) {
            return "error|1";
        }
        if (file.getSize() > 5 * 1024 * 1024) {
            return "error|5";
        }

        String result = upload(file, path);
//        String result = fileUpload(file, path);
        if(result.equals("failed")) {
            return "error|3";
        } else {
            return result;
        }
    }

    private String upload(MultipartFile file, String path) {
        String tmpPath = fileLocalPath + path;
        String name = file.getOriginalFilename();
        int a = -1;
        try {
            String extName = "";
            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }
            name = new Date().getTime() + getRandNum(6).toString() + extName;
            File f = new File(tmpPath, name);
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            a = postHttp(fileServerURL, "file" + path, f);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        if (a == -1) {
            return "failed";
        } else {
            return accessFileURL + path + name;
        }
    }
    private String fileUpload(MultipartFile file, String path) {
        String tmpPath = fileLocalPath + path;
        String name = file.getOriginalFilename();
        int a = -1;
        try {
            String extName = "";
            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }
            File f = new File(tmpPath, name);
            FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            a = postHttp(fileServerURL, "file" + path, f);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        if (a == -1) {
            return "failed";
        } else {
            return accessFileURL + path + name;
        }
    }


    private int postHttp(String url, String path, File file) throws IOException {

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
        mEntityBuilder.addBinaryBody("file", file);
        mEntityBuilder.addTextBody("path", path);
        httppost.setEntity(mEntityBuilder.build());
        HttpResponse resp = httpClient.execute(httppost);
        int code = resp.getStatusLine().getStatusCode();
        if (200 == code) {
            return 0;
        } else {
            return -1;
        }
    }

    private char[] getRandNum(int n) {
        char[] rand = new char[n];
        String str = "23456789qwertyuipkjhgfdsacvbnmQWERTYUPLKJHGFDSACVBNM";
        for (int i = 0; i < n; i++) {
            Random rd = new Random();
            int index = rd.nextInt(str.length());
            rand[i] = str.charAt(index);
        }
        return rand;
    }
}
